package org.wso2.carbon.registry.lifecycle.accenture.sample.handlers;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.governance.api.util.GovernanceConstants;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.handlers.Handler;
import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.registry.eventing.events.ResourceUpdatedEvent;
import org.wso2.carbon.registry.lifecycle.accenture.sample.ServiceConstant;
import org.wso2.carbon.registry.lifecycle.accenture.sample.utils.CustomEmailMessageUtil;
import org.wso2.carbon.registry.lifecycle.accenture.sample.utils.NotificationUtil;
import org.wso2.carbon.registry.lifecycle.accenture.sample.utils.SubscriptionUtil;
import org.wso2.carbon.registry.lifecycle.accenture.sample.utils.Utils;

import java.util.HashMap;
import java.util.List;


/**
 * This handler used to send notifications when service request
 */
public class ServiceRequestNotificationHandler extends Handler {
    private static final Log log = LogFactory.getLog(ServiceRequestNotificationHandler.class);
    @Override
    public void put(RequestContext requestContext) throws RegistryException {

        Resource resource = requestContext.getResource();
        String mediaType = resource.getMediaType();
        String resourcePath = requestContext.getResourcePath().getPath();
        Registry registry = requestContext.getRegistry();
        int branchInt =resourcePath.indexOf("branches");
        // used this logic to prevent execution when service modifying
        // at the movement we are checking "branches" world in resource path to stop execution when promoting the service
        if (GovernanceConstants.SERVICE_MEDIA_TYPE.equals(mediaType)
            && !registry.resourceExists(resourcePath) && branchInt == -1) {
            //Adding the property which determines who created the service
            resource.setProperty(ServiceConstant.CREATED_BY, NotificationUtil.getLoggedInUserEmail());

            HashMap<String, List<String>> emailMap = (new SubscriptionUtil()).initSubscriptionMap(requestContext);
            //initialize the resource contexts to fill all the email addresses to HashMaps
            if (emailMap != null) {
                // get the Architecture mail address
                List<String> emailList = emailMap.get(SubscriptionUtil.ARCHITECT_ID);
                for (String email : emailList) {
                    //send message to notify new service request
                    sendMail(email, requestContext);
                }
            }
        }
    }

    private void sendMail(String email, RequestContext requestContext) {
        String emailMsg = null;
        //get subscription resource
        String subscriptionPath = Utils.getSubscriptionPath(email);
        UserRegistry reg = null;
        try {
            Utils.setDefaultNotificationServiceURL(requestContext.getSystemRegistry().getEventingServiceURL(null));
            reg = (UserRegistry) requestContext.getSystemRegistry();
        } catch (RegistryException e) {
            e.printStackTrace();
        }
        try {
            //get service name to construct the email message
            String serviceName = Utils.getServiceNameFromResource(requestContext.getResource());
            //get backEnd server URL to construct the resource URL
            String backEndURL = NotificationUtil.getBackendServerUrl();
            String servicePath = backEndURL + "carbon/resources/resource.jsp?region=region3&item=resource_browser_menu&path="
                    + requestContext.getResourcePath().getPath();
            emailMsg = CustomEmailMessageUtil.getNewRequestPromoteMessage(serviceName, servicePath);

        } catch (RegistryException e) {
            e.printStackTrace();
        }

        ResourceUpdatedEvent<String> resourceUpdatedEvent = new ResourceUpdatedEvent<String>(emailMsg);
        resourceUpdatedEvent.setResourcePath(subscriptionPath);

        if (reg != null) {
            resourceUpdatedEvent.setTenantId(reg.getTenantId());
        }
        try {
            NotificationUtil.notify(resourceUpdatedEvent, requestContext.getSystemRegistry(),
                    requestContext.getResourcePath().getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
